var instance;
var routeStart = "routeStart";
var routeEnd = "routeEnd";
//gaoqihang 保存方法
function saveCanvasData() {
    var connects = [];
    $.each(instance.getAllConnections(), function (idx, connection) {
        connects.push({
            color: connection.getPaintStyle('label').fillStyle,
            label: connection.getOverlay('label').label,
            sourceId: connection.sourceId,
            targetId: connection.targetId,
            ruleseq: $(connection).data("ruleseq")//保存连线的ruleseq
        });
    });
    var blocks = [];
    $("#topocontent .elebox").each(function (idx, elem) {
        var $elem = $(elem);
        blocks.push({
            newid: $elem.attr('id'),
            itemseq: $elem.data("itemseq"),
            itemid: $elem.data("itemid"),
            itemname: $elem.data("itemname"),
            itemX: parseInt($elem.css("left")),
            itemY: parseInt($elem.css("top"))
        });
    });
    serliza = JSON.stringify(connects) + "&" + JSON.stringify(blocks);
    return serliza;
}

// JavaScript Document
$(function () {

    //-------------------编辑(start)-------------------
    var topocontent = $('#topocontent'),
		lefticon = $('#lefticon'),
		lefticon2 = $('#lefticon2'),
		linewrap = $('#linewrap');

    //连接样式
    var lineColorArr = new Array();
    var relationArr = new Array();
    linewrap.find("li").each(function (index, item) {
        lineColorArr[index] = $(this).data("itemcolor");
        relationArr[index] = $(this).data("itemid");
    })
    instance = jsPlumb.getInstance({
        Endpoint: ["Dot", { radius: 2 }],
        ConnectionOverlays: [
            ["Arrow", { location: 1, id: "arrow", length: 10, foldback: 0.8, width: 10 }],
            ["Label", { label: "to", id: "label", cssClass: "labelstyle" }]
        ],
        DragOptions: { zIndex: 2000 },
        Container: "topocontent"
    });
    var labelTxt = relationArr[0],
	    lineColor = lineColorArr[0],
        lineWidth = 3,
	    pstyle = {
	        Endpoint: ["Dot", { radius: 2 }],
	        paintStyle: {
	            strokeStyle: lineColor,
	            fillStyle: lineColor
	        },
	        connector: ["Flowchart", { stub: [0, 0], gap: 2, cornerRadius: 5, alwaysRespectStubs: true }],
	        connectorStyle: {
	            lineWidth: lineWidth,
	            strokeStyle: lineColor,
	        },
	        maxConnections: -1
	    };

    linewrap.find('span').each(function (i) {//点解切换关系
        var $this = $(this);
        $this.click(function () {
            linewrap.find('span').removeClass('focus');
            $this.addClass('focus');
            labelTxt = relationArr[i];
            lineColor = lineColorArr[i];
        });
    });

    $(document).on('click', '#topocontent div.elebox', function () {
        var thisId = $(this).prop("id");
        layer.msg("确认删除此元素及其链接吗？", {
            time: 0,
            btn: ['确定', '取消'],
            yes: function (index) {
                layer.close(index);
                if (thisId == routeStart || thisId == routeEnd) {
                    layer.alert("此节点不允许删除！");
                }
                else {
                    $("#list" + thisId).css("display", "");//gaoqihang 元素删除后显示到列表
                    instance.removeAllEndpoints(thisId);
                    instance.remove(thisId);
                }
            }
        });
    });
    instance.bind("connection", function (info) {//更改label关系
        info.connection.getOverlay("label").setLabel(labelTxt);
    });
    instance.bind("connectionDrag", function (info) {//更改连接链颜色
        info.setPaintStyle({ fillStyle: lineColor, strokeStyle: lineColor, lineWidth: lineWidth });
    });
    instance.bind("connectionDragStop", function (info) {
        if (info.sourceId == info.targetId || !isValidLine(info)) {
            //连线不符合要求
            instance.detach(info);
        }
        else {
            $(info).data("ruleseq", $("#linewrap .focus").data("itemseq"));
            info.unbind('click');
            info.bind('click', function () {
                detachLine(info);
            });
        };
    });
    function detachLine(info) {//删除连接
        layer.msg("确认删除此链接吗？", {
            time: 0,
            btn: ['确定', '取消'],
            yes: function (index) {
                layer.close(index);
                instance.detach(info);
            }
        });
    }
    function renderConnect(newid) {//渲染
        instance.draggable(newid);
        instance.doWhileSuspended(function () {
            var isFilterSupported = instance.isDragFilterSupported();
            if (isFilterSupported) {
                instance.makeSource(newid, { filter: ".dragPoint", anchor: "Continuous" }, pstyle);
            } else {
                var eps = jsPlumb.getSelector(".dragPoint");
                for (var i = 0; i < eps.length; i++) {
                    var e = eps[i], p = e.parentNode;
                    instance.makeSource(e, { parent: p, anchor: "Continuous" }, pstyle);
                }
            }
        });
        instance.makeTarget(newid, { dropOptions: { hoverClass: "dragHover" }, anchor: "Continuous" }, pstyle);
    }

    //拖动创建元素
    lefticon.children('div.iconitems').draggable({
        helper: 'clone',
        scope: 'topo'
    });
    lefticon2.children('div.iconitems').draggable({
        helper: 'clone',
        scope: 'topo'
    });
    topocontent.droppable({
        scope: 'topo',
        drop: function (event, ui) {
            ui.draggable.css("display", "none");//gaoqihang 拖拽成功后，隐藏原DOM
            //ui.draggable.remove();
            //获取基本元素与参数
            var $this = $(this),
				dragui = ui.draggable,
				fatop = parseInt($this.offset().top),
				faleft = parseInt($this.offset().left),
				uitop = parseInt(ui.offset.top),
				uileft = parseInt(ui.offset.left),
                itemseq = dragui.data('itemseq'),
                itemid = dragui.data('itemid'),
                itemname = dragui.data('itemname'),
                itemnewid = dragui.data('itemnewid');

            //插入元素组织
            var newstyle = 'left:' + (uileft - faleft >= 0 ? uileft - faleft : 0) + 'px;top:' + (uitop - fatop >= 0 ? uitop - fatop : 0) + 'px',
                newid = itemnewid,
                str = '<div class="elebox" id="' + newid + '" data-itemseq="' + itemseq + '" data-itemid="' + itemid + '" data-itemname="' + itemname + '" style="' + newstyle + '"><span class="dragPoint">' + itemid + '</span><span class="dragPoint">' + itemname + '</span></div>';//gaoqihang 给创建的元素添加自定义属性，删除时可以还原原元素

            $this.append(str);
            renderConnect(newid);
            instance.revalidate(newid);
            $("#" + newid).draggable({ containment: "parent" });
        }
    });
    //-------------------编辑(end)-------------------

    //检测连接线是否符合要求  gaoqihang
    function isValidLine(line) {
        if (line.sourceId == routeEnd || line.sourceId.indexOf("route_") > -1 || line.targetId == routeStart)//起始点是途程或者End节点，或结束点是Start节点
            return false;
        if (line.sourceId == routeStart) {//如果起始点是Start，则终止点必须是站点
            if (line.targetId.indexOf('step_') < 0)
                return false;
        }
        var isValid = true;
        var lines=instance.getAllConnections();
        $.each(lines, function (index, connection) {
            if (((line.sourceId == connection.sourceId && line.getOverlay('label').label == connection.getOverlay('label').label)//起始站点已存在一条该类型连接线
                || ((line.sourceId == connection.sourceId && line.targetId == connection.targetId) || (line.sourceId == connection.targetId && line.targetId == connection.sourceId)))//起始和终止站点之间已经存在一条连线
                && lines.length != index + 1) {//排除新添加的线
                isValid = false;
                return false;
            }
        });
        return isValid;
    }

    /*----------------初始化画布数据 begin-------------------*/
    editData($("#routeData").val());
    function editData(response) {
        if (response == '') {
            //return false;
            response = '[]&[{"newid":"' + routeStart + '","itemseq":0,"itemid":"step0","itemname":"Start","itemX":20,"itemY":20},{"newid":"' + routeEnd + '","itemseq":-1,"itemid":"step-1","itemname":"End","itemX":100,"itemY":100}]';
        }
        var list = eval(response.split('&')[0]),
            blocks = eval(response.split('&')[1]),
            htmlText = "",
            conn = "";
        //------------插入元素-------------
        //var isHasStart = false;
        for (var i in blocks) {
            var viewstyle = 'left:' + blocks[i].itemX + 'px;top:' + blocks[i].itemY + 'px;',
                newid = blocks[i].newid,
                itemseq = blocks[i].itemseq,
                itemid = blocks[i].itemid,
                itemname = blocks[i].itemname;
            if (newid == routeStart || newid == routeEnd) {
                htmlText = htmlText + '<div class="elebox" id="' + newid + '" data-itemseq="' + itemseq + '" data-itemid="' + itemid + '" data-itemname="' + itemname + '" style="' + viewstyle + 'background-color:black;width:25px;height:25px;border-radius: 50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;"><span class="dragPoint">' + itemname + '</span></div>';
                //isHasStart = true;
            }
            else {
                htmlText = htmlText + '<div class="elebox" id="' + newid + '" data-itemseq="' + itemseq + '" data-itemid="' + itemid + '" data-itemname="' + itemname + '" style="' + viewstyle + '"><span class="dragPoint">' + itemid + '</span><span class="dragPoint">' + itemname + '</span></div>';
            }
        };
        ////给之前没有开始和结束的测试数据添加开始和结束按钮，正式上线时可删除
        //if (!isHasStart) {
        //    var blocks2 = eval('[{"newid":"' + routeStart + '","itemseq":0,"itemid":"step0","itemname":"Start","itemX":20,"itemY":20},{"newid":"' + routeEnd + '","itemseq":-1,"itemid":"step-1","itemname":"End","itemX":100,"itemY":100}]');
        //    for (var i in blocks2) {
        //        var viewstyle = 'left:' + blocks2[i].itemX + 'px;top:' + blocks2[i].itemY + 'px;',
        //            newid = blocks2[i].newid,
        //            itemseq = blocks2[i].itemseq,
        //            itemid = blocks2[i].itemid,
        //            itemname = blocks2[i].itemname;
        //        htmlText = htmlText + '<div class="elebox" id="' + newid + '" data-itemseq="' + itemseq + '" data-itemid="' + itemid + '" data-itemname="' + itemname + '" style="' + viewstyle + 'background-color:black;width:25px;height:25px;border-radius: 50%;-moz-border-radius: 50%;-webkit-border-radius: 50%;"><span class="dragPoint">' + itemname + '</span></div>';
        //    }
        //}
        topocontent.html(htmlText);

        //------------默认连接-------------
        var windowsDrag = jsPlumb.getSelector("#topocontent .elebox");
        renderConnect(windowsDrag);
        //------------更改样式-------------
        for (var i in list) {
            var conor = instance.connect({ source: list[i].sourceId, target: list[i].targetId });
            conor.getOverlay("label").setLabel(list[i].label);
            conor.setPaintStyle({ fillStyle: list[i].color, strokeStyle: list[i].color, lineWidth: lineWidth });
            $(conor).data("ruleseq", list[i].ruleseq);//输出连线的ruleseq gaoqihang
            conor.bind('click', function () {
                detachLine(this);
            });
        };
        $("div .elebox").draggable({ containment: "parent" });
    }
    /*----------------初始化画布数据 end-------------------*/
});


